package com.jy.adscm.operation.base.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.base.bean.TaskWorkAttachment;
import com.jy.adscm.operation.base.mapper.mysql.TaskWorkAttachmentMapper;
import com.jy.adscm.operation.base.service.TaskWorkAttachmentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;

/**
 * <p>
 * 附件 服务实现类
 * </p>
 *
 * @author zyl
 * @since 2020-07-28
 */
@Service
public class TaskWorkAttachmentServiceImpl extends ServiceImpl<TaskWorkAttachmentMapper, TaskWorkAttachment> implements TaskWorkAttachmentService {
     @Autowired
    JyUserMapper jyUserMapper;
    @Value("${ly.upload.imagePath}")
    private  String imagePath;
    @Value("${ly.upload.imageUrl}")
    private  String imageUrl;
   @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteTaskWorkAttachment(Integer id, Token token) throws AdscmSystemException {
        TaskWorkAttachment taskWorkAttachment = super.selectById(id);
        if (!token.getUser().getId().toString().equals(taskWorkAttachment.getCreator())){
             throw new AdscmSystemException("不能删除");
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(taskWorkAttachment.getPath(),null)){
            File file=new File(imagePath+taskWorkAttachment.getPath());
             if (file.exists()){
                 file.delete();
             }
        }
       boolean b = super.deleteById(id);
       return b;
    }

    @Override
    public List<TaskWorkAttachment> selectTaskWorkAttachment(Integer pid, Token token) {
        Wrapper<TaskWorkAttachment> wrapper=new EntityWrapper<>();
        wrapper.eq("pid",pid);
        List<TaskWorkAttachment> taskWorkAttachments = super.selectList(wrapper);
        for (TaskWorkAttachment taskWorkAttachment : taskWorkAttachments) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskWorkAttachment.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(taskWorkAttachment.getCreator());
                 taskWorkAttachment.setCreatorName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskWorkAttachment.getPath(),null)){
                taskWorkAttachment.setPath(imageUrl+taskWorkAttachment.getPath());
            }
        }


        return taskWorkAttachments;
    }
}
